package com.zyc.studentstudy.simple

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import kotlin.coroutines.cancellation.CancellationException

/**
 * Created by zhangyuncai on 2021/11/11.
 */
abstract class SimpleActivity : FragmentActivity() {

    //方便打印日志的标签
    val TAG = this::class.java.simpleName

    //快捷注册EventBus
    var isRegisterEventBus = false

    fun getContext(): Context {
        return this
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val databingView = useDatabing()
        if (databingView != null) {
            setContentView(databingView)
        } else {
            setContentView(getLayoutId())
        }
        if (isRegisterEventBus && !EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        initView()
        initEvent()
        initData()
    }

    protected open fun useDatabing(): View? {
        return null
    }

    protected fun getLayoutId(): Int {
        return 0
    }

    protected abstract fun initView()

    protected abstract fun initEvent()

    protected abstract fun initData()

    /**
     * 延时一段时间收到消息
     * @param time 延时时间,毫秒
     * @param callback 延时时间已到回调
     */
    protected fun delayTime(time: Long, callback: ((Boolean) -> Unit)): Job {
        return lifecycleScope.launch {
            try {
                delay(time)
                callback.invoke(true)
            } catch (e: CancellationException) {
                // 静默处理取消异常，不打印日志
            } catch (throwable: Throwable) {
            }
        }
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        super.onDestroy()
    }
}
